package com.qq.weixin.model;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.qq.weixin.enums.ErrorCode;

public class ResultInfo {
	private boolean success;
	private int errcode;
	private String errmsg;

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public int getErrcode() {
		return errcode;
	}

	public void setErrcode(int errcode) {
		this.errcode = errcode;
	}

	public String getErrmsg() {
		return errmsg;
	}

	public void setErrmsg(String errmsg) {
		this.errmsg = errmsg;
	}

	public static ResultInfo convert(JsonElement element) {
		ResultInfo resultInfo = new ResultInfo();
		if (element == null) {
			resultInfo.setSuccess(ErrorCode.E0.getCode() == resultInfo
					.getErrcode());
			return resultInfo;
		}
		JsonObject jsonObject = element.getAsJsonObject();
		JsonElement errcodeElement = jsonObject.get("errcode");
		if (errcodeElement != null) {
			resultInfo.setErrcode(errcodeElement.getAsInt());
			JsonElement errmsgElement = jsonObject.get("errmsg");
			resultInfo.setErrmsg(errmsgElement.getAsString());
		}

		resultInfo
				.setSuccess(ErrorCode.E0.getCode() == resultInfo.getErrcode());

		return resultInfo;
	}

	public static ResultInfo convert(JSON json) {
		ResultInfo resultInfo = JSON.toJavaObject(json, ResultInfo.class);
		resultInfo
				.setSuccess(ErrorCode.E0.getCode() == resultInfo.getErrcode());
		return resultInfo;
	}

	public static ResultInfo convert(String jsonstr) {
		ResultInfo resultInfo = JSON.parseObject(jsonstr, ResultInfo.class);
		resultInfo
				.setSuccess(ErrorCode.E0.getCode() == resultInfo.getErrcode());
		return resultInfo;
	}

	@Override
	public String toString() {
		return "ResultInfo [success=" + success + ", errcode=" + errcode
				+ ", errmsg=" + errmsg + "]";
	}

}
